package com.hxw.android.utils;

import java.io.*;
import java.nio.charset.Charset;

public class WindowCmdCtrl {

    private Runtime runtime;
    private String charset = "GBK";//编码格式
    private boolean isPrintCmd = false;

    public WindowCmdCtrl(){
        runtime = Runtime.getRuntime();
    }

    /**
     * 设置编码格式
     * @param charset
     */
    public void setCharset(String charset){
        if (charset!=null&&!charset.isEmpty()){
            this.charset = charset;
        }
    }

    /**
     * 是否打印执行的命令
     * @param isPrintCmd
     */
    public void isPrintCmd(boolean isPrintCmd){
        this.isPrintCmd = isPrintCmd;
    }

    /**
     * 对文件夹进行cmd操作
     *
     * @param cmd
     * @param envp
     * @param dir
     * @return
     */
    public String exec(String cmd, String[] envp, String dir){

        if (!cmd.startsWith("cmd /c")){
            cmd = "cmd /c "+cmd;
        }

        if (isPrintCmd){
            System.out.println(dir+">"+cmd);
        }

        try {
            return getReply(runtime.exec(cmd, envp, new File(dir)));
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 执行cmd
     * @param cmd 命令
     * @return
     */
    public String exec(String cmd){
        if (!cmd.startsWith("cmd /c")){
            cmd = "cmd /c "+cmd;
        }

        if (isPrintCmd){
            System.out.println(cmd);
        }

        try {
            return getReply(runtime.exec(cmd));
        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 获取应答
     * @param process
     * @return
     */
    private String getReply(Process process){

        try{
            BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.forName(charset)));
            StringBuilder builder = new StringBuilder();

            String line;
            while ((line=br.readLine())!=null) {
                builder.append(line);
                builder.append("\r\n");
            }

            BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream(),Charset.forName(charset)));
            String errorLine;

            while ((errorLine = error.readLine())!=null) {
                builder.append(errorLine);
                builder.append("\r\n");
            }

            return builder.toString();
        }catch (Exception e){
            e.printStackTrace();
        }

        return null;
    }

    public void close(){
        if (runtime!=null){
            runtime.gc();
        }
    }
}